import { MenuModel } from "@/api/modules/auth"
import { create } from "zustand"
import { devtools, persist, createJSONStorage } from "zustand/middleware"

interface State {
  darkMode: boolean // 是否开启dark模式
  collapsed: boolean // 是否折叠菜单
  lang: string // 语言
  userId?: string | null
  menuList: MenuModel[]
  accessToken: string | any
  refreshToken: string | any
}
interface Actions {
  setDarkMode: (darkMode: boolean) => void
  setCollapsed: (collapsed: boolean) => void
  setLang: (lang: string) => void
  setUserId: (user: string | null) => void
  setPathname: (pathname: string) => void
  setMenuList: (menuList: MenuModel[]) => void
  setAccessToken: (token: string | null) => void
  setRefreshToken: (token: string | null) => void
}

export const useGlobalStore = create<State & Actions & any>()(
  devtools(
    persist(
      (set) => {
        return {
          darkMode: false,
          collapsed: false,
          lang: "zh",
          userId: null,
          menuList: [],
          accessToken: null,
          refreshToken: null,
          setDarkMode: (darkMode: boolean) =>
            set({
              darkMode
            }),
          setCollapsed: (collapsed: boolean) =>
            set({
              collapsed
            }),
          setLang: (lang: string) => set({ lang }),
          setUserId: (userId: string | null) => set({ userId }),
          setPathname: (pathname: string) =>
            set({
              pathname
            }),
          setMenuList: (menuList: MenuModel[]) => {
            set({ menuList })
          },
          setAccessToken: (accessToken: string | null) =>
            set({
              accessToken
            }),
          setRefreshToken: (refreshToken: string | null) =>
            set({
              refreshToken
            })
        }
      },
      {
        name: "globalStore",
        storage: createJSONStorage(() => localStorage)
      }
    ),
    { name: "globalStore" }
  )
)
